package com.nami.store.biz.privatehismsgs.repository.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nami.store.api.request.message.HisMsgQryRequest;
import com.nami.store.api.response.message.MessageDTO;
import com.nami.store.biz.privatehismsgs.repository.PrivateHisMsgsRepository;
import com.nami.store.domain.PrivateHisMsgsDO;
import com.nami.store.mapper.PrivateHisMsgsMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author lbc
 * @since 2024-06-15
 */
@Service
@Slf4j
@AllArgsConstructor
public class PrivateHisMsgsServiceImpl implements PrivateHisMsgsRepository {

    private final PrivateHisMsgsMapper baseMapper;

    @Override
    public boolean save(PrivateHisMsgsDO msgs) {
        baseMapper.insert(msgs);
        return Boolean.TRUE;
    }

    @Override
    public Map<String, MessageDTO> getMsgs(List<String> c2cMsgIds) {

        if (CollUtil.isEmpty(c2cMsgIds)) {
            return new HashMap<>();
        }
        List<PrivateHisMsgsDO> msgList = baseMapper.selectList(new LambdaQueryWrapper<PrivateHisMsgsDO>()
            .in(PrivateHisMsgsDO::getMsgId, c2cMsgIds));
        if (CollUtil.isEmpty(msgList)) {
            return new HashMap<>();
        }

        List<MessageDTO> messages = new ArrayList<>();
        MessageDTO messageVO;
        for (PrivateHisMsgsDO item : msgList) {
            messageVO = new MessageDTO();
            messageVO.setPayload(item.getPayload());
            messageVO.setPayloadType(item.getPayloadType());
            messageVO.setSeq(item.getSeq());

            messageVO.setId(item.getMsgId());
            messageVO.setSendTime(item.getSendTime());

            messages.add(messageVO);
        }

        return messages.stream().collect(Collectors.toMap(MessageDTO::getId, Function.identity()));

    }

    @Override
    public List<PrivateHisMsgsDO> getHisMsgs(HisMsgQryRequest request) {
        List<PrivateHisMsgsDO> result = baseMapper.selectList(new LambdaQueryWrapper<PrivateHisMsgsDO>()
            .eq(PrivateHisMsgsDO::getAppKey, request.getAppKey())
            .eq(PrivateHisMsgsDO::getConverId, request.getConverId())
            .lt(request.getLastSeq() != null, PrivateHisMsgsDO::getSeq, request.getLastSeq())
            .orderByDesc(PrivateHisMsgsDO::getSeq)
            .last(" limit " + request.getPageSize())
        );

        return result;
    }
}
